<template>
	<div ref="chartContainer" :style="{ height, width }" class="sc-echarts-container"></div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, nextTick, onActivated, onDeactivated } from 'vue';
import * as echarts from 'echarts';
import T from './echarts-theme-T.js';

// 注册主题
echarts.registerTheme('T', T);

interface Props {
	height?: string;
	width?: string;
	nodata?: boolean;
	option?: echarts.EChartsCoreOption;
}

const props = withDefaults(defineProps<Props>(), {
	height: '100%',
	width: '100%',
	nodata: false,
	option: () => ({})
});

const chartContainer = ref<HTMLElement>();
let chartInstance: echarts.ECharts | null = null;
let isDestroyed = false;
let isActivated = true;
let resizeHandler: (() => void) | null = null;

// 初始化图表
const initChart = async () => {
	if (isDestroyed || !chartContainer.value) return;
	
	try {
		// 如果已存在实例，先销毁
		if (chartInstance) {
			chartInstance.dispose();
			chartInstance = null;
		}
		
		// 创建新实例
		chartInstance = echarts.init(chartContainer.value, 'T');
		
		// 设置初始选项
		if (props.option && Object.keys(props.option).length > 0) {
			chartInstance.setOption(props.option, true);
		}
		
		// 设置resize监听器
		setupResizeListener();
		
	} catch (error) {
		console.error('ECharts初始化失败:', error);
	}
};

// 设置窗口大小调整监听
const setupResizeListener = () => {
	if (resizeHandler) {
		window.removeEventListener('resize', resizeHandler);
	}
	
	resizeHandler = () => {
		if (chartInstance && !isDestroyed && isActivated) {
			try {
				chartInstance.resize();
			} catch (error) {
				console.error('ECharts resize失败:', error);
			}
		}
	};
	
	window.addEventListener('resize', resizeHandler);
};

// 更新图表选项
const updateChart = async () => {
	if (isDestroyed || !chartInstance) return;
	
	try {
		if (props.option && Object.keys(props.option).length > 0) {
			// 直接使用原始选项，不需要unwrap
			chartInstance.setOption(props.option, true);
		}
	} catch (error) {
		console.error('ECharts更新失败:', error);
	}
};

// 监听选项变化
watch(
	() => props.option,
	async () => {
		if (!isDestroyed) {
			await nextTick();
			if (!chartInstance) {
				await initChart();
			} else {
				await updateChart();
			}
		}
	},
	{ deep: true }
);

// 监听尺寸变化
watch(
	() => [props.height, props.width],
	async () => {
		if (!isDestroyed) {
			await nextTick();
			if (chartInstance) {
				chartInstance.resize();
			}
		}
	}
);

// 组件挂载
onMounted(async () => {
	await nextTick();
	await initChart();
});

// 组件激活（用于keep-alive）
onActivated(async () => {
	isActivated = true;
	if (chartInstance && !isDestroyed) {
		await nextTick();
		try {
			chartInstance.resize();
		} catch (error) {
			console.error('ECharts激活resize失败:', error);
		}
	}
});

// 组件停用（用于keep-alive）
onDeactivated(() => {
	isActivated = false;
});

// 组件卸载
onUnmounted(() => {
	isDestroyed = true;
	
	// 清理resize监听器
	if (resizeHandler) {
		window.removeEventListener('resize', resizeHandler);
		resizeHandler = null;
	}
	
	// 销毁图表实例
	if (chartInstance) {
		try {
			chartInstance.dispose();
		} catch (error) {
			console.error('ECharts销毁失败:', error);
		}
		chartInstance = null;
	}
});

// 暴露方法给父组件使用
defineExpose({
	getInstance: () => chartInstance,
	resize: () => {
		if (chartInstance && !isDestroyed) {
			chartInstance.resize();
		}
	},
	refresh: initChart
});
</script>

<style scoped>
.sc-echarts-container {
	position: relative;
	overflow: hidden;
}
</style>